const Base = require('./base.js');
const xlsx = require('node-xlsx');
const fs = require('fs');
module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.order = this.model("taoke/order");
		this.queue = this.model("taoke/queue");
		this.asset = this.model("system/asset");
		this.user = this.model("system/user");

	}
	async indexAction() {
		if(this.isGet) {

			return this.display();
		}

		let posts = this.post();
		let where = {
			'order_status': ['!=', "订单失效"]
		};

		if(!think.isEmpty(posts.order_sn)) {
			where.order_sn = ['like', '%' + posts.order_sn + '%'];
		}
		if(!think.isEmpty(posts.status)) {
			where.order_status = posts.status;
		}

		let fields = "id,order_sn,goods_name,order_amount,income_ratio,effect_prediction,order_status,balance_time,create_time,buyer_rate,buyer_commission,recommend_rate,recommend_commission";
		const data = await this.order.joinUserTable(posts, where, fields);
		return this.json(data);

	}

	async editAction() {

		let posts = this.post();
		let order = await this.order.findOne(posts.id);
		let user = await this.user.where({
			username: posts.username
		}).find();
		if(think.isEmpty(user)) {
			return this.fail("用户不存在");
		}

		let asset = await this.asset.where({
			user_id: user.id
		}).find();
		if(think.isEmpty(asset)) {
			return this.fail("用户资产不存在");
		}

		if(think.isEmpty(order.user_id)) {

			let row = await this.order.bindOrder(order, asset);
			if(row == 0) {
				return this.fail("绑单失败");
			}

			return this.success("修改成功");

		} else {
			if(order.user_id == user.id) {
				return this.fail("绑单人未变更");
			}
			let row = await this.order.clearBind(order);
			if(row == 0) {
				return this.fail("解绑失败");
			}
			let rows = await this.order.bindOrder(order, asset);
			if(rows == 0) {
				return this.fail("绑单失败");
			}
			return this.success("修改成功");

		}

	}

	async clearAction() {

		let posts = this.post();
		let order = await this.order.findOne(posts.id);
		let row = await this.order.clearBind(order);
		if(row == 0) {
			return this.fail("未绑单");
		}

		return this.success("修改成功");

	}

	async balanceAction() {

		let posts = this.post();
		let order = await this.order.findOne(posts.id);

		if(order.order_status == 3) {
			return this.fail("该订单已结算");
		}

		if(!think.isEmpty(order.user_id)) {
			await this.order.orderBalance(order);
		}

		await this.order.setOne(order.id, {
			order_status: 3
		});

		return this.success("结算成功");

	}

	//通过xls更新订单
	async updateExcelAction() {

		const alimama = think.service("alimama");
		let orderExcel = await alimama.getExcelOrder();

		await think.timeout(3000);

		const orders = (xlsx.parse(fs.readFileSync(orderExcel)))[0].data;

		console.log(orderExcel);
		let nameTransfer = {
			"创建时间": "create_time",
			"点击时间": "click_time",
			"商品信息": "goods_name",
			"商品ID": "goods_id",
			"掌柜旺旺": "wangwang",
			"所属店铺": "shop",
			"商品数": "goods_number",
			"商品单价": "goods_price",
			"订单状态": "order_status",
			"订单类型": "order_type",
			"收入比率": "income_ratio",
			"分成比率": "divided_ratio",
			"付款金额": "order_amount",
			"效果预估": "effect_prediction",
			"结算金额": "balance_amount",
			"预估收入": "estimated_revenue",
			"结算时间": "balance_time",
			"佣金比率": "commission_ratio",
			"佣金金额": "commission_amount",
			"技术服务费比率": "servefee_ratio",
			"补贴比率": "subsidy_ratio",
			"补贴金额": "subsidy_amount",
			"补贴类型": "subsidy_type",
			"成交平台": "order_platform",
			"第三方服务来源": "serve_from",
			"订单编号": "order_sn",
			"类目名称": "category",
			"来源媒体ID": "site_id",
			"广告位ID": "adzone_id",
			"来源媒体名称": "media_name",
			"广告位名称": "adv_name"
		};

		let nameArray = orders[0];
		for(let i = 0; i < nameArray.length; i++) {
			nameArray[i] = nameTransfer[nameArray[i]];
		}
		console.log(nameArray);
		let ordersJson = [];

		for(let x = 1; x < orders.length; x++) {
			let orderJson = {};
			for(let y = 0; y < orders[x].length; y++) {
				orderJson[nameArray[y]] = orders[x][y];

			}
			ordersJson.push(orderJson);
		}

		if(!think.isEmpty(ordersJson)) {
			await this.order.updateOrderByExcel(ordersJson);

			await this.order.where({
				is_updated: 1
			}).update({
				is_updated: 0
			});

		}
		return this.success("订单更新成功");

	}

	async updateJsonAction() {

		const alimama = think.service("alimama");
		let orders = await alimama.getJsonOrder();

		if(!think.isEmpty(orders)) {
			await this.order.updateOrderByJson(orders);

			await this.order.where({
				is_updated: 1
			}).update({
				is_updated: 0
			});

		}
		return this.success("订单更新成功");

	}

	async updateApiAction() {
        let posts = this.post();
		const alimama = think.service("alimama");

		let nowTime = new Date().valueOf();
		let period = Number(posts.period);
		let monthTime = period * 24 * 3600 * 1000;
		let time = 600 * 1000;
		for(let i = 0; i < monthTime; i = i + time) {
			let orderTime = think.datetime(nowTime - monthTime + i);
			console.log(orderTime);
			await think.timeout(200);
			let orders = await alimama.getOrders('', orderTime);
			if(!think.isEmpty(orders)) {
				await this.order.updateOrder(orders);

			}

		}

		

		return this.success("订单更新成功");

	}
	
	
	
};